﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

using ManageSystemClient.HttpService;
using ManageSystemClient.Record;
using ManageSystemClient.WindowService;

using Microsoft.Extensions.DependencyInjection;

namespace ManageSystemClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainPage : Page
    {
        private readonly IServiceProvider serviceProvider;
        private readonly ManageService manageService;
        private List<Student> allStudents;
        private readonly Window owner;
        public MainPage(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            this.serviceProvider = serviceProvider;
            manageService = serviceProvider.GetRequiredService<ManageService>();
            allStudents = new();
            owner = Window.GetWindow(this);
        }

        private void InitDataGrid(object sender, RoutedEventArgs e) => InitData();

        private async Task HandleError(Func<Task> tr, Action? fin = default)
        {
            try
            {
                idText.IsEnabled = false;
                nameText.IsEnabled = false;
                ageText.IsEnabled = false;
                majorText.IsEnabled = false;
                addButton.IsEnabled = false;
                deleteButton.IsEnabled = false;
                modifyButton.IsEnabled = false;
                queryButton.IsEnabled = false;
                refreshButton.IsEnabled = false;
                progressBar.Visibility = Visibility.Visible;
                await tr();
            }
            catch (AggregateException e)
            {
                Dispatcher.Invoke(() => MBox.ShowError(owner, e.GetBaseException().Message));
            }
            finally
            {
                fin?.Invoke();
                idText.IsEnabled = true;
                nameText.IsEnabled = true;
                ageText.IsEnabled = true;
                majorText.IsEnabled = true;
                addButton.IsEnabled = true;
                deleteButton.IsEnabled = true;
                modifyButton.IsEnabled = true;
                queryButton.IsEnabled = true;
                refreshButton.IsEnabled = true;
                progressBar.Visibility = Visibility.Hidden;
            }
        }

        private void InitData()
        {
            _ = HandleError(async () => allStudents = await manageService.GetStudentsAsync(),
                () => Dispatcher.Invoke(() => dataGrid.ItemsSource = allStudents));
        }

        private Student? CovToStu()
        {
            if (!uint.TryParse(idText.Text, out uint id))
            {
                _ = MBox.ShowError(owner, "Invalid ID.");
                return null;
            }
            if (!uint.TryParse(ageText.Text, out uint age))
            {
                _ = MBox.ShowError(owner, "Invalid age.");
                return null;
            }
            return new(id, nameText.Text, age, majorText.Text);
        }

        private void Add(object sender, RoutedEventArgs e)
        {
            _ = HandleError(async () =>
              {
                  var stu = CovToStu();
                  if (stu == null) return;
                  await manageService.AddStudentAsync(stu);
                  allStudents.Add(stu);
                  dataGrid.ItemsSource = allStudents;
              });
        }

        private void Delete(object sender, RoutedEventArgs e)
        {
            _ = HandleError(async () =>
            {
                var stu = CovToStu();
                if (stu == null) return;
                await manageService.DeleteStudentAsync(stu.StudentId);
                allStudents.Remove(allStudents.Find(s => s.StudentId == stu.StudentId)!);
                dataGrid.ItemsSource = allStudents;
            });
        }

        private void Modify(object sender, RoutedEventArgs e)
        {
            _ = HandleError(async () =>
            {
                var stu = CovToStu();
                if (stu == null) return;
                await manageService.ModifyStudentAsync(stu);
                allStudents.Remove(allStudents.Find(s => s.StudentId == stu.StudentId)!);
                allStudents.Add(stu);
                dataGrid.ItemsSource = allStudents;
            });

        }

        private void Query(object sender, RoutedEventArgs e)
        {
            var res = allStudents;
            if (uint.TryParse(idText.Text, out uint id))
                res = res.FindAll(s => s.StudentId == id);
            else
            {
                if (nameText.Text != "")
                    res = res.FindAll(s => s.Name.Contains(nameText.Text));
                if (uint.TryParse(ageText.Text, out uint age))
                    res = res.FindAll(s => s.Age == age);
                if (majorText.Text != "")
                    res = res.FindAll(s => s.Major.Contains(majorText.Text));
            }
            dataGrid.ItemsSource = res;
        }

        private void Refresh(object sender, RoutedEventArgs e) => InitData();
    }
}
